package com.example.authcenter.utils;

import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import sun.misc.BASE64Decoder;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Date;


/**
 * 生成token工具类
 */
public class JwtUtils {

    //私钥
    private static String rsa_private_key = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBANZJvezzbKVLEhr1epqzPZ0E8wcRM3//5wYILBgOi6vj0vJ4kyajncpPt/hYrOF0odaTNrEKdUJI4ZHumiCBreE/gjlB7rEgsmuRDz4vdvCljBQyb75/jeW1dhQ+tuUCVI4WpN7z0PAQ+NNr+kKlt3s/octeLbZ/Exf7RrLi8AfBAgMBAAECgYBdNPIRkMgfFYoog8HybChOlgqHdmnqMQrxyrgzNpB2EcB9iwimc+B8UTR6J0f7QNnsFVhipWPfkwfai+gqX32bglN9Hhysm5CVWMJj5IYg7DJs5tHs3JlnWsqvIYtD3YxJri36YgW/F5FDvByJB115/fUmOfj2QihTIUEkq8TTiQJBAO7RcwcXjzEay3TTGqzpORhOctZZUNUp2MQ/6t04/CagrfqcbMMfojbj4hC0jvMNY14lXBxynguk9PzaqQuHLHMCQQDltH9OD4YoKL5BRevyr0qUIC6he2QIoWf8RniWXagednkm8D9TA+EfETsqF58UVR/8geAK5x29R/nG3aStGQH7AkBzICMMcy4DJQCZk77TRibQ8dhoPmw6Jk8p5AorlPHxCRp1qny/33sKbPaoyPH0dyrE0svBpvtLb7zuO9asCQDDAkAyAyuYll6yTbSmx4+IxkuplpwwgooUKvhWAA3vRzL8dvUH2lUfQP/54KmOD5iON76AHtLl7M4X0Rz8BHP/UCuTAkB0OO1qMAcUb1YDIXDWfICTwcLcgrRczh/hdYBcvKJFJpuLKDIc3Hma8ubEbakAzr0yUrS7+jFKY4pzYlLrZedm";

    /**
     * 登录过期时间（24小时）
     */
    private static final long TOKEN_EXPIRE_TIME = 1000*60*60*24;


    /**
     * 如果使用非对称加密算法 RSA
     * 字符串转私钥
     * @return
     */
    private static PrivateKey stringToPrivateKey(String rsa_private_key){
        PrivateKey privateKey = null;
        try {
            PKCS8EncodedKeySpec bobPrivateKeySpec = new PKCS8EncodedKeySpec(new BASE64Decoder().decodeBuffer(rsa_private_key));
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            privateKey = keyFactory.generatePrivate(bobPrivateKeySpec);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }
        System.out.println("私钥对象--：" + privateKey);
        return privateKey;
    }


    /**
     * 生成token
     * @return
     */
    public static String generateToken(){
        PrivateKey privateKey = stringToPrivateKey(rsa_private_key);
        JSONObject json = new JSONObject();
        json.put("userId","123");
        json.put("userName","mhg");
        String token = Jwts.builder()
                .setSubject(json.toJSONString())
                .setHeaderParam("typ","JWT")
                .setExpiration(new Date(System.currentTimeMillis() + TOKEN_EXPIRE_TIME))
                .signWith(SignatureAlgorithm.RS512,privateKey)
                .compact();
        //返回token
        System.out.println("生成的token为--："+ token);
        return token;
    }

    /**
     * 测试生成token
     * @param args
     */
    public static void main(String[] args) {
        //生成token
        generateToken();
    }

}
